package framework.system.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import framework.core.controller.BaseAction;
import framework.core.util.Kit;
import framework.core.util.ListRange;
import framework.system.entity.SysUser;
import framework.system.service.IMenuService;
import framework.system.service.IUserService;

/** 
 * @ClassName: LoginController 
 * @Description: 登陆Controller 
 * @author: Ching Wang
 * @date 2013-5-18 下午1:56:48 
 *
 */
@Controller
@RequestMapping("/loginctrl")
public class LoginController extends BaseAction{

	@Resource private IUserService userService;
	@Resource private IMenuService menuService;
	
	/**
	 * @Title: login 
	 * @Description: 登陆方法
	 * @param account 用户帐号
	 * @param password 用户密码
	 * @param session
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/login")
	public void login(String account, String password, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception{
		try {
			ListRange<SysUser> listRange = new ListRange<SysUser>();
			if(Kit.isNotNull(account) && Kit.isNotNull(password)){
				DetachedCriteria criteria = DetachedCriteria.forClass(SysUser.class);
				String ss=Kit.getMd5(password);
				System.out.println("ss==="+ss);
				criteria.add(Restrictions.eq("password", ss));
				criteria.add(Restrictions.eq("account", account));
				List<SysUser> users = userService.findByCriteria(criteria);
				if(users != null && users.size() > 0){
					session.setAttribute("user", users.get(0));
 				   
					session.setAttribute("auth",menuService.loadAut(users.get(0).getId()));
					
					//System.out.print("auth"+session.getAttribute("auth") +"     ");
					listRange.setMessage("登录成功。");
					listRange.setSuccess(true);
				}
				else{
					listRange.setMessage("帐号或密码不正确，请确认。");
					listRange.setSuccess(false);
				}
			}
			else{
				listRange.setMessage("帐号或密码不能为空，请确认。");
				listRange.setSuccess(false);
			}
			outJson(response, listRange, "yyyy-MM-dd");
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * @Title: logout 
	 * @Description: 退出登陆
	 * @param session
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/logout")
	public void logout(HttpSession session, HttpServletResponse response) throws Exception{
		clearSession(session);
		ListRange<Object> listRange = new ListRange<Object>();
		listRange.setMessage("退出成功.");
		listRange.setSuccess(true);
		outJson(response, listRange, "yyyy-MM-dd");
	}
}
